import { Context } from 'koa';
const { getCitiesByquery, getInfoById, getAllProvs } = require('../service/area.service')
const { invalidAreaId, isEmpty, provError } = require('../constants/err.type')

interface queryInfo {
    cityName?: string,
    provName?: string
}

class AreaController {
    // 获取单个城市（通过省名和城市名）
    public async getCities(ctx: Context) {
        try {
            let { cityName, provName }: queryInfo = ctx.query;
            if (cityName && provName) {
                const res: any = await getCitiesByquery(cityName, provName)
                if(res) {
                    ctx.body = {
                        code: 200,
                        message: '获取城市成功',
                        ...res
                    }
                } else {
                    ctx.body = {
                        code: 404,
                        message: '查无此城市',
                    }
                }
            } else {
                return ctx.app.emit('error', isEmpty, ctx)
            }
        } catch (error) {
            console.error('获取城市失败', error)
        }
    }
    // 通过id获取城市或者区县
    public async getAreaById(ctx: Context) {
        try {
            const id = ctx.params.id
            const res: any = await getInfoById(id);
            if(res) {
                ctx.body = {
                    code: 200,
                    message: '根据id获取地区成功',
                    result: res
                }
            } else {
                return ctx.app.emit('error', invalidAreaId, ctx)
            }
        } catch (error) {
            console.error('根据id获取地区失败', error)
        }
    }
    // 获取所有的省
    public async getProvs(ctx: Context) {
        try {
            const res: any = await getAllProvs();
            if(res) {
                ctx.body = {
                    code: 200,
                    message: '获取省份成功',
                    ...res
                }
            } else {
                return ctx.app.emit('error', provError, ctx)
            }
        } catch (error) {
            console.error('获取省份失败', error)
        }
    }
}

module.exports = new AreaController();